package com.hucii.app.net;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.util.ByteArrayBuffer;

import com.hucii.app.json.CXJson;
import com.hucii.app.json.CXJsonNode;
import com.hucii.app.json.handler.BaseHandler;

/**
 * 网络请求工具类
 * 
 * @author
 * 
 */
public class HttpTools {

	public static final String TAG_ROOT = "Request";
	public static final String TAG_MESSAGE_NAME = "MessageName";

	public static final String TAG_SID = "Sid";

	public static final String TAG_MESSAGE = "Message";

	public static final String TAG_CLIENT = "Client";

	public static Object getObjectWithJson(String url, BaseHandler handler) {

		AgentHttpClient mHttpClient = null;
		ByteArrayBuffer bab = new ByteArrayBuffer(100);

		try {

			RequestEntity qe = new RequestEntity();
			qe.setMethod(NetTask.METHOD_GET);
			qe.setUrl(url);

			mHttpClient = new AgentHttpClient();
			AgentInputStream ais = mHttpClient.execute(qe, true);
			
			DataInputStream dis = new DataInputStream(ais.getImpl());
			byte[] buffer = new byte[256];
			int len = 0;
			//
			while ((len = dis.read(buffer)) != -1) {
				bab.append(buffer, 0, len);
			}

			CXJson cXjson = new CXJson();
			CXJsonNode root = cXjson.loadJsonFromNet(bab.toByteArray());

			return handler.parseJson(root);

		} catch (Exception e) {

			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 通过网络获取返回的内容（为字符串）
	 * 
	 * @param methodName
	 * @param pairs
	 * @return
	 * @throws Exception
	 */
	public static String getString(Map<String, String> pairs) throws Exception {
		AgentHttpClient mHttpClient = null;
		try {
			mHttpClient = new AgentHttpClient();
			RequestEntity requestEntity = new RequestEntity();

			Set<Entry<String, String>> entrySet = pairs.entrySet();
			for (Entry<String, String> entry : entrySet) {
				requestEntity.addParam(entry.getKey(), entry.getValue());
			}
			AgentInputStream ais = mHttpClient.execute(requestEntity);
			return XmlParserManager.getString(ais.getImpl());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			if (mHttpClient != null) {
				mHttpClient.close();
			}
		}
	}

	/**
	 * 通过网络获取返回的链接（为字符串）
	 * 
	 * @param methodName
	 * @param pairs
	 * @return
	 * @throws Exception
	 */
	public static String getURL(Map<String, String> pairs) throws Exception {
		AgentHttpClient mHttpClient = null;
		try {
			mHttpClient = new AgentHttpClient();
			RequestEntity requestEntity = new RequestEntity();

			Set<Entry<String, String>> entrySet = pairs.entrySet();
			for (Entry<String, String> entry : entrySet) {
				requestEntity.addParam(entry.getKey(), entry.getValue());
			}
			return mHttpClient.getURL(requestEntity);

		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			if (mHttpClient != null) {
				mHttpClient.close();
			}
		}
	}

	/**
	 * 通过网络获取返回的实体bean
	 * 
	 * @param methodName
	 * @param pairs
	 * @return
	 * @throws Exception
	 */
	public static <T> T getBeanByPullXml(Map<String, String> pairs, Class<T> clazz) throws Exception {
		AgentHttpClient mHttpClient = null;
		try {
			mHttpClient = new AgentHttpClient();
			RequestEntity requestEntity = new RequestEntity();
			// requestEntity.setMethod(Task.METHOD_POST);
			requestEntity.setMethod(NetTask.METHOD_GET);
			Set<Entry<String, String>> entrySet = pairs.entrySet();
			for (Entry<String, String> entry : entrySet) {
				requestEntity.addParam(entry.getKey(), entry.getValue());
			}
			AgentInputStream ais = mHttpClient.execute(requestEntity);
			return XmlParserManager.getBean(ais.getImpl(), clazz);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			if (mHttpClient != null) {
				mHttpClient.close();
			}
		}
	}

	/**
	 * 通过网络获取返回的实体bean集合
	 * 
	 * @param methodName
	 * @param pairs
	 * @return
	 * @throws Exception
	 */
	public static <T> ArrayList<T> getListByPullXml(Map<String, String> pairs, String root, Class<T> clazz) throws Exception {
		AgentHttpClient mHttpClient = null;
		try {
			mHttpClient = new AgentHttpClient();
			RequestEntity requestEntity = new RequestEntity();

			Set<Entry<String, String>> entrySet = pairs.entrySet();
			for (Entry<String, String> entry : entrySet) {
				requestEntity.addParam(entry.getKey(), entry.getValue());
			}
			AgentInputStream ais = mHttpClient.execute(requestEntity);
			return XmlParserManager.getBeanList(ais.getImpl(), root, clazz);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			if (mHttpClient != null) {
				mHttpClient.close();
			}
		}
	}



	/**
	 * 上传图片
	 * 
	 * @param filePath
	 *            图片地址
	 * @param username
	 * @return
	 */
	public static String uploadFile(String filePath) {

		return uploadFile(filePath, 0);
	}

	/**
	 * 
	 * @param filePath
	 * @param falg
	 *            0，默认，1随手拍
	 * @return随手拍
	 */
	public static String uploadFile(String filePath, int falg) {
		String result = null;
		BufferedReader rd = null;
		URL u = null;
		URLConnection conn = null;
		OutputStream os = null;
		try {

			// String url="http://linju.client.3g.soufun.com/agentupload";
			String url = IAgentRequest.HTTP_SCHEME + "://" + IAgentRequest.HTTP_HOST + "/UploadPhoto";
			if (falg == 1) {
				url = IAgentRequest.HTTP_SCHEME + "://" + IAgentRequest.HTTP_HOST + "/AgentPhoto";
			}
			u = new URL(url);
			conn = u.openConnection();
			conn.setReadTimeout(15 * 1000);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			if (filePath != null) {
				os = conn.getOutputStream();
			}
			FileInputStream fis = new FileInputStream(filePath);
			byte[] buffer = new byte[4096];
			int length = -1;

			while ((length = fis.read(buffer)) != -1) {
				os.write(buffer, 0, length);
			}

			rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			StringBuffer strBuffer = new StringBuffer();
			String rn = System.getProperty("line.separator");
			while ((result = rd.readLine()) != null) {
				strBuffer.append(result + rn);
			}
			result = strBuffer.toString();
			strBuffer.delete(0, strBuffer.length());
			if (fis != null)
				fis.close();
			if (rd != null)
				rd.close();
			if (os != null)
				os.close();
			conn = null;
			u = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (result != null) {
			result = result.replaceAll("<.*?>", "").trim();
			result = result.replaceAll("[%]amp", "&");
		}
		return result;
	}

	/**
	 * 通过网络获取返回的InputStream
	 * 
	 * @param pairs
	 * @return
	 * @throws Exception
	 */
	public static InputStream getInputStream(Map<String, String> pairs) throws Exception {
		AgentHttpClient mHttpClient = null;
		try {
			mHttpClient = new AgentHttpClient();
			RequestEntity requestEntity = new RequestEntity();
			// requestEntity.setMethod(Task.METHOD_POST);
			requestEntity.setMethod(NetTask.METHOD_GET);
			Set<Entry<String, String>> entrySet = pairs.entrySet();
			for (Entry<String, String> entry : entrySet) {
				requestEntity.addParam(entry.getKey(), entry.getValue());
			}
			AgentInputStream ais = mHttpClient.execute(requestEntity);
			return ais.getImpl();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			// if (mHttpClient != null) {
			// mHttpClient.close();
			// }
		}
	}
}